package com.lg.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lg.dao.UserInfoRepository;
import com.lg.entiry.UserInfo;

@Controller
public class HomeController {
	@Autowired
	private UserInfoRepository userInfoRepository;
	
	
	 /**
     * 登出  这个方法没用到,用的是shiro默认的logout
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session, Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","安全退出！");
        return "login";
    }

    @RequestMapping({"/","/index"})
    public String index(Map<String, Object> map){
    	  List<UserInfo> findAll = userInfoRepository.findAll();
          map.put("users", findAll);
          Subject subject = SecurityUtils.getSubject();
          Object principal = subject.getPrincipal();
          if(principal instanceof UserInfo) {
        	  UserInfo userInfo  = (UserInfo) principal;
          }
        return"index";
    }
    /**
     * 用户添加;
     * @return
     */
    @RequestMapping(value="/doRegister",method=RequestMethod.POST)
    public String userInfoAdd(UserInfo userInfo){
    	String password = userInfo.getPassword();
    	String salt = userInfo.getSalt();
    	 SimpleHash simpleHash = new SimpleHash(new Md5Hash().getAlgorithmName(), password,  ByteSource.Util.bytes(userInfo.getCredentialsSalt()), 1);
    	 userInfo.setPassword(simpleHash.toString());
    	 userInfoRepository.save(userInfo);
    	 return "redirect:/index";
    }
    @RequestMapping(value="/login",method=RequestMethod.GET)
    public String login(HttpServletRequest request, Map<String, Object> map) throws Exception{
        return "login";
    }
    @RequestMapping(value="/register",method=RequestMethod.GET)
    public String register(HttpServletRequest request, Map<String, Object> map) throws Exception{
        return "register";
    }
    @RequestMapping(value="/doLogin",method=RequestMethod.POST)
    public String doLogin(UserInfo userInfo,Map map) {
    	Subject subject = SecurityUtils.getSubject();
    	AuthenticationToken token = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getPassword());
		try {
			subject.login(token );
			 // 判断当前用户是否登录
            if (subject.isAuthenticated() == true) {
//            	 List<UserInfo> findAll = userInfoRepository.findAll();
//               map.put("users", findAll);
//               UserInfo userInfo1 = (UserInfo) subject.getPrincipal();
//               map.put("user", userInfo1);
                return "redirect:/index";
            }
           return "login";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			map.put("msg", e.getMessage());
			return "login";
		}
    }
    @RequestMapping("/403")
    public String unauthorizedRole(){
        System.out.println("------没有权限-------");
        return "403";
    }

}